package com.scisoft.scan.control.shelves;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.nlscan.android.scan.ScanManager;
import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.control.ScanHelper;
import com.scisoft.scan.control.stock.StockFlowActivity;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.depot.AreaBean;
import com.scisoft.scan.data.shelves.ShelvesInfoBean;
import com.scisoft.scan.data.shelves.ShelvesPartInfoBean;
import com.scisoft.scan.data.stock.StockFlowBean;
import com.scisoft.scan.data.stock.StockFlowQueryBean;
import com.scisoft.scan.data.stock.StockInfoCheckBean;
import com.scisoft.scan.data.stock.StockInfoPositionBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_Depot;
import com.scisoft.scan.ws.WebServiceHelper_Shelves;
import com.scisoft.scan.ws.WebServiceHelper_Stock;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

public class ShelvesEditActivity extends Activity {

    private ImageView iv_Back; //返回按钮
    private TextView tv_save; //保存按钮
    private TextView tv_add; //货物上架按钮
    //表单项
    private ClearEditText et_hjh;//货架号控件
    private TextView tv_depotName;
    private Spinner spin_area;//库区列表控件
    private View l_part;
    private TextView tv_count;

    //库区
    private List<String> areaList = new ArrayList<>();//库区字典
    private List<AreaBean> areaBeanList = new ArrayList<>();//库区字典
    private int selectedAreaNo = 0;
    //数据
    private ShelvesInfoBean shelvesInfoBean;
    private List<ShelvesPartInfoBean> shelvesPartInfoBeanList;
    //列表
    ShelvesPartAdapter shelvesAdapter;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    float lastY = 0;
    private EditText et_position;

    @Override
    @SuppressLint("ClickableViewAccessibility")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_shelves_edit);

        //初始化扫码
        init();

        //参数传递
        Intent intent = getIntent();
        shelvesInfoBean = (ShelvesInfoBean) intent.getSerializableExtra("data");
        //表单项
        et_hjh = findViewById(R.id.et_hjh);
        tv_depotName = findViewById(R.id.tv_depotName);
        tv_count = findViewById(R.id.tv_count);
        l_part = findViewById(R.id.l_part);
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShelvesEditActivity.this.finish();
            }
        });
        //保存
        tv_save = findViewById(R.id.tv_save);
        tv_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GetData();
                CommonUtil.showPress(ShelvesEditActivity.this);
                SaveTask saveTask = new SaveTask(ShelvesEditActivity.this);
                saveTask.execute();
            }
        });
        //货物上架
        tv_add = findViewById(R.id.tv_add);
        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //货物上架
                Intent intent = new Intent(ShelvesEditActivity.this, ShelvesPartQueryActivity.class);
                intent.putExtra("data", shelvesInfoBean);
                startActivityForResult(intent, REQUEST_PJSJ);
            }
        });

        //列表
        mRecyclerView = findViewById(R.id.lv_data);
        shelvesAdapter = new ShelvesPartAdapter(ShelvesEditActivity.this);
        shelvesAdapter.setMultiPage(false);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;
        shelvesAdapter.setItemLayout(R.layout.item_shelvespartdetail, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //滚动的时候清空左滑按钮
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(event.getY() - lastY) > 5)
                            shelvesAdapter.clearLeftMenuList();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(shelvesAdapter);

        QueryData();
    }

    private final int REQUEST_PJSJ = 0;//配件上架
    private final int REQUEST_LS = 1;//配件流水

    //返回当前界面
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_PJSJ:
                QueryData();
                break;
            case REQUEST_LS:
                break;
        }
    }

    //设置数据,包括：仓库、货位、货架号
    private void SetData(Context context) {
        //货架号
        et_hjh.setText(shelvesInfoBean.shelvesName);
        tv_depotName.setText(shelvesInfoBean.depotName);
        //库区，其中库区的ID在查询接口已经设置好
        if (selectedAreaNo >= 0 && selectedAreaNo < areaBeanList.size()) {
            spin_area.setSelection(selectedAreaNo, true);
        }
    }

    //获取数据,包括：仓库、货位、货架号
    private void GetData() {
        //货架号
        shelvesInfoBean.shelvesName = et_hjh.getUpperText().toString();
        //库区
        if (selectedAreaNo >= 0 && selectedAreaNo < areaBeanList.size()) {
            shelvesInfoBean.areaId = areaBeanList.get(selectedAreaNo).areaId;
            shelvesInfoBean.areaName = areaBeanList.get(selectedAreaNo).areaName;
        } else {
            Toast.makeText(getApplicationContext(), "请选择库区", Toast.LENGTH_LONG).show();
        }
    }

    //查询货架上配件列表
    private void QueryData() {
        CommonUtil.showPress(ShelvesEditActivity.this);
        QueryShelvesPartTask queryShelvesPartTask = new QueryShelvesPartTask(ShelvesEditActivity.this);
        queryShelvesPartTask.execute();
    }

    //绑定配件数据
    private void BindData(Context context) {
        if (shelvesPartInfoBeanList == null || shelvesPartInfoBeanList.size() == 0) {
            l_part.setVisibility(View.INVISIBLE);
            mRecyclerView.setVisibility(View.INVISIBLE);
        } else {
            l_part.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.VISIBLE);
            //数量
            tv_count.setText(String.valueOf(shelvesPartInfoBeanList.size()) + "项");
            //数据
            shelvesAdapter.clearLeftMenuList();
            shelvesAdapter.clearAddItem(shelvesPartInfoBeanList);
        }
    }

    //绑定货区字典数据
    private void SetSpanArea(Context context) {
        spin_area = findViewById(R.id.spin_area);
        areaList.clear();
        for (int i = 0; i < areaBeanList.size(); i++) {
            areaList.add(areaBeanList.get(i).areaName);
        }
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.style_spinner, areaList);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_area.setAdapter(adapter2);
        spin_area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedAreaNo = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //查询货架上配件服务，包含了仓库字典项的服务在里面
    class QueryShelvesPartTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryShelvesPartTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //根据所选择的仓库查询货位字典项
                areaBeanList = WebServiceHelper_Depot.DEPOT_12(shelvesInfoBean.depotId);
                //根据当前货位的ID，设置当前货位
                if(areaBeanList!=null) {
                    for (int i = 0; i < areaBeanList.size(); i++) {
                        if (areaBeanList.get(i).areaId.equals(shelvesInfoBean.areaId)) {
                            selectedAreaNo = i;
                            break;
                        }
                    }
                }
                //查询列表数据
                shelvesPartInfoBeanList = WebServiceHelper_Shelves.SHELVES_04(shelvesInfoBean.shelvesId);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                SetSpanArea(mcontext);//货区
                SetData(mcontext);
                BindData(mcontext);//货架配件
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //保存数据服务
    class SaveTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        SaveTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //保存
                msg = WebServiceHelper_Shelves.SHELVES_03(shelvesInfoBean);

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_LONG).show();

            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }


    //适配器相关功能
    class ShelvesPartAdapter extends CommonAdapter<ShelvesPartInfoBean> {

        //构造函数
        public ShelvesPartAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final ShelvesPartInfoBean shelvesPartInfoBean, int position) {
            //获取相应索引的ItemBean对象
            final ShelvesPartInfoBean bean = mList.get(position);
            //配件代码
            TextView tv_partCode = holder.getView(R.id.tv_partCode);
            //配件名称
            TextView tv_partName = holder.getView(R.id.tv_partName);
            //供应商
            TextView tv_supplierCode = holder.getView(R.id.tv_supplierCode);
            //原厂件
            TextView tv_supplierName = holder.getView(R.id.tv_supplierName);
            //数量
            TextView tv_count = holder.getView(R.id.tv_count);
            //图片
            ImageView iv_img = holder.getView(R.id.iv_img);

            //设置控件的对应属性值
            tv_partCode.setText(bean.partCode);
            tv_partName.setText(bean.partName);
            tv_supplierCode.setText(bean.supplierCode);
            tv_supplierName.setText(bean.supplierName);
            tv_count.setText(String.valueOf(bean.partCount));
            if (bean.partImageUrl != null && !bean.partImageUrl.equals("")) {
                Picasso.with(mContext).load(bean.partImageUrl).into(iv_img);
            } else {
                iv_img.setImageDrawable(getResources().getDrawable(R.drawable.ic_noimage));
            }
            //按钮(查询库存流水)
            TextView tv_flow = holder.getView(R.id.tv_flow);
            tv_flow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonUtil.showPress(ShelvesEditActivity.this);
                    QueryFlowTask queryFlowTask = new QueryFlowTask(ShelvesEditActivity.this, bean.partId, bean.supplierCode, bean.supplierName);
                    queryFlowTask.execute();
                }
            });
            //按钮(盘点)
            TextView tv_check = holder.getView(R.id.tv_check);
            tv_check.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alert_check(bean);
                }
            });
            //按钮(查询修改货架)
            TextView tv_shelves = holder.getView(R.id.tv_shelves);
            tv_shelves.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alert_shelves(bean);
                }
            });
            //按钮(下架)
            TextView tv_delete = holder.getView(R.id.tv_delete);
            tv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonUtil.showPress(ShelvesEditActivity.this);
                    DeleteTask deleteTask = new DeleteTask(ShelvesEditActivity.this, bean);
                    deleteTask.execute();
                }
            });
        }

        //弹出盘点窗口
        private void alert_check(final ShelvesPartInfoBean shelvesPartInfoBean) {
            //1.创建一个Dialog对象,去除标题栏
            final Dialog mDialog = new Dialog(mContext);
            mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            //2.填充布局,将自定义布局设置进去
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View dialogView = inflater.inflate(R.layout.dialog_partinfo_check, null);
            mDialog.setContentView(dialogView);
            //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            Window window = mDialog.getWindow();
            lp.copyFrom(window.getAttributes());
            lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
            mDialog.show();
            window.setAttributes(lp);
            //4、设置点击其它地方不让消失弹窗
            mDialog.setCancelable(false);
            //5、初始化控件
            TextView tv_pjshow = dialogView.findViewById(R.id.tv_pjshow);
            tv_pjshow.setText(shelvesPartInfoBean.partName + " "  + shelvesPartInfoBean.supplierName );
            TextView tv_zmshow = dialogView.findViewById(R.id.tv_zmshow);
            tv_zmshow.setText("账面 (" + shelvesInfoBean.depotName + "  " + shelvesInfoBean.areaName + " "  + shelvesInfoBean.shelvesName + ")");//账面 (仓库 库区 货位)
            TextView tv_kycount = dialogView.findViewById(R.id.tv_kycount);
            tv_kycount.setText(String.valueOf(shelvesPartInfoBean.canUseCount));
            TextView tv_kccount = dialogView.findViewById(R.id.tv_kccount);
            tv_kccount.setText(String.valueOf(shelvesPartInfoBean.partCount));
            TextView tv_zy = dialogView.findViewById(R.id.tv_zy);//成本
            tv_zy.setText(String.valueOf(shelvesPartInfoBean.partCount - shelvesPartInfoBean.canUseCount));
            final EditText et_spcount = dialogView.findViewById(R.id.et_spcount);

            TextView tv_ok = dialogView.findViewById(R.id.tv_ok);
            tv_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //按下确定键后的事件
                    StockInfoCheckBean stockInfoCheckBean = new StockInfoCheckBean();
                    stockInfoCheckBean.stockId = shelvesPartInfoBean.stockId;
                    stockInfoCheckBean.partId = shelvesPartInfoBean.partId;
                    stockInfoCheckBean.partNo = shelvesPartInfoBean.partNo;
                    stockInfoCheckBean.partCode = shelvesPartInfoBean.partCode;
                    stockInfoCheckBean.manufacturer = shelvesPartInfoBean.supplierCode;
                    stockInfoCheckBean.manufacturerName = shelvesPartInfoBean.supplierName;
                    stockInfoCheckBean.checkCount = et_spcount.getText().toString();

                    CommonUtil.showPress(ShelvesEditActivity.this);
                    CheckTask checkTask = new CheckTask(ShelvesEditActivity.this, stockInfoCheckBean);
                    checkTask.execute();
                    mDialog.dismiss();
                }
            });
            TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDialog.dismiss();
                }
            });
        }

        //弹出修改货架窗口
        private void alert_shelves(final ShelvesPartInfoBean shelvesPartInfoBean) {
            //1.创建一个Dialog对象,去除标题栏
            final Dialog mDialog = new Dialog(mContext);
            mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            //2.填充布局,将自定义布局设置进去
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View dialogView = inflater.inflate(R.layout.dialog_partinfo_shelves, null);
            mDialog.setContentView(dialogView);
            //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            Window window = mDialog.getWindow();
            lp.copyFrom(window.getAttributes());
            lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
            mDialog.show();
            window.setAttributes(lp);
            //4、设置点击其它地方不让消失弹窗
            mDialog.setCancelable(false);
            //5、初始化控件
            TextView tv_depot = dialogView.findViewById(R.id.tv_depot);
            tv_depot.setText(shelvesInfoBean.depotName + " " + shelvesInfoBean.areaName);//仓库 + 库区
            TextView tv_position = dialogView.findViewById(R.id.tv_position);//货架
            tv_position.setText(shelvesInfoBean.shelvesName);
            et_position = dialogView.findViewById(R.id.et_position);

            TextView tv_ok = dialogView.findViewById(R.id.tv_ok);
            tv_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //按下确定键后的事件
                    StockInfoPositionBean stockInfoPositionBean = new StockInfoPositionBean();
                    stockInfoPositionBean.stockId = shelvesPartInfoBean.stockId;
                    stockInfoPositionBean.partId = shelvesPartInfoBean.partId;
                    stockInfoPositionBean.partName = shelvesPartInfoBean.partName;
                    stockInfoPositionBean.partCode = shelvesPartInfoBean.partCode;
                    stockInfoPositionBean.supplierId = shelvesPartInfoBean.supplierId;
                    stockInfoPositionBean.supplierCode = shelvesPartInfoBean.supplierCode;
                    stockInfoPositionBean.supplierName = shelvesPartInfoBean.supplierName;
                    stockInfoPositionBean.newPosition = et_position.getText().toString();

                    CommonUtil.showPress(ShelvesEditActivity.this);
                    PositionTask positionTask = new PositionTask(ShelvesEditActivity.this, stockInfoPositionBean);
                    positionTask.execute();
                    mDialog.dismiss();
                }
            });
            TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDialog.dismiss();
                }
            });
        }
    }

    //配件下架数据服务
    class DeleteTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private ShelvesPartInfoBean shelvesPartInfoBean;

        DeleteTask(Context context, ShelvesPartInfoBean shelvesPartInfoBean) {
            super();
            mcontext = context;
            this.shelvesPartInfoBean = shelvesPartInfoBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //查询列表数据
                msg = WebServiceHelper_Shelves.SHELVES_09(shelvesPartInfoBean.relId, shelvesPartInfoBean.stockId);
                //刷新列表
                shelvesPartInfoBeanList = WebServiceHelper_Shelves.SHELVES_04(shelvesInfoBean.shelvesId);

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //查询库存流水服务
    class QueryFlowTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String partId;
        private String manufacturer;
        private String manufacturerName;
        private StockFlowBean stockFlowBean;

        QueryFlowTask(Context context, String partId,String manufacturer,String manufacturerName) {
            super();
            mcontext = context;
            this.partId = partId;
            this.manufacturer = manufacturer;
            this.manufacturerName = manufacturerName;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //查询列表数据
                StockFlowQueryBean stockFlowQueryBean = new StockFlowQueryBean();
                stockFlowQueryBean.partNo = partId;
                stockFlowQueryBean.manufacturer = manufacturer;
                stockFlowQueryBean.manufacturerName = manufacturerName;
                stockFlowBean = WebServiceHelper_Stock.STOCK_02(stockFlowQueryBean);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                Intent intent = new Intent(ShelvesEditActivity.this, StockFlowActivity.class);
                intent.putExtra("data", stockFlowBean);
                startActivityForResult(intent, REQUEST_LS);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //盘点服务
    class CheckTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private StockInfoCheckBean stockInfoCheckBean;

        CheckTask(Context context, StockInfoCheckBean stockInfoCheckBean) {
            super();
            mcontext = context;
            this.stockInfoCheckBean = stockInfoCheckBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_Stock.STOCK_07(stockInfoCheckBean);
                if (msg.contains("成功")) {
                    //刷新列表
                    shelvesPartInfoBeanList = WebServiceHelper_Shelves.SHELVES_04(shelvesInfoBean.shelvesId);
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //修改货架服务
    class PositionTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private StockInfoPositionBean stockInfoPositionBean;

        PositionTask(Context context, StockInfoPositionBean stockInfoPositionBean) {
            super();
            mcontext = context;
            this.stockInfoPositionBean = stockInfoPositionBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_Shelves.SHELVES_10(stockInfoPositionBean);
                if (msg.contains("成功")) {
                    //刷新列表
                    shelvesPartInfoBeanList = WebServiceHelper_Shelves.SHELVES_04(shelvesInfoBean.shelvesId);
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }


    //以下为扫码相关
    //初始化
    private void init(){
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    //查询条码服务
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (barCodeBean == null || barCodeBean.barType == BarCodeBean.BAR_UNKNOWN) {
                    Toast.makeText(ShelvesEditActivity.this, "无效二维码：" + barCode, Toast.LENGTH_LONG).show();
                } else if (barCodeBean.barType == BarCodeBean.BAR_PART) {
                    Toast.makeText(ShelvesEditActivity.this, "请扫描货架", Toast.LENGTH_LONG).show();
                } else {
                    et_position.setText(barCodeBean.shelvesBean.shelvesName);
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //扫码处理
    private void ScanData(String barCode) throws Exception {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(ShelvesEditActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        //IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        //registerReceiver(mResultReceiver, intFilter);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result
        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result
        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
                // 处理扫码结果
                try {
                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
                    ScanData(decodedData);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(ShelvesEditActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };

}
